package com.time.workshop.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.time.workshop.API;
import com.time.workshop.App;
import com.time.workshop.BaseConstant;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.adapter.DingZuoAdapter;
import com.time.workshop.bean.BaseListResponse;
import com.time.workshop.bean.CountyList;
import com.time.workshop.bean.ShopList;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.IDropdownItemClickListener;
import com.time.workshop.utils.Log;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.ScreenSizeUtil;
import com.time.workshop.utils.TitlePopupwindow;
import com.time.workshop.view.RefreshViewLoadMoreProxy;
import com.time.workshop.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;

public class DingZuoActivity extends SuperActivity implements OnLoadDataActionListener{
	private PullToRefreshListView xlistView;
	@V
	private ImageView img_login_back;
	@V
	private TextView tv_login_rsg,tv_title;
	@V
	private RelativeLayout dingzuo_titlebar_content,empty_relat;
	private DingZuoAdapter madapter;

	private List<CountyList> countyList = new ArrayList<CountyList>();
	private List<ShopList> shopList = new ArrayList<ShopList>();
	private List<ShopList> shopList1 = new ArrayList<ShopList>();
	/** 返回数据总体的实体类 */
	private class Response extends BaseListResponse<CountyList>{};
	private Response mResponse;
	private class ResponseShop extends BaseListResponse<ShopList>{};
	private ResponseShop mResponseShop;

	private String county_id;
	private int page = 1;
	private RefreshViewLoadMoreProxy mLoadMoreProxy;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_dingzuo);
		Injector.getInstance().inject(this);
		App.street_id = "";
		App.street_name = "";
		App.county_id = "";
		App.county_name = "";
		

		init();

		
	}

	private void init() {
		
		img_login_back.setOnClickListener(this);
		tv_login_rsg.setOnClickListener(this);
		if (BaseConstant.DINGZUO == App.getInstance().type) {
			tv_title.setText("订座");
			tv_login_rsg.setVisibility(View.VISIBLE);
			reqCounty();
		}else if (BaseConstant.GUAHAO == App.getInstance().type) {
			tv_title.setText("挂号");
		}
		reqStoreList(true);
		xlistView = (PullToRefreshListView) findViewById(R.id.xlistView);
		
		xlistView.setEmptyView(empty_relat);
		xlistView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
		mLoadMoreProxy = new RefreshViewLoadMoreProxy(xlistView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);

		xlistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent;
				if (BaseConstant.DINGZUO == App.getInstance().type) {
					intent = new Intent(DingZuoActivity.this,WantDingZuoActivity.class);
				}else {
					intent = new Intent(DingZuoActivity.this,WantGuaHaoActivity.class);
				}
				intent.putExtra("shoplist", shopList1.get(position-1));
				startActivity(intent);
			}
		});
		//tv_login_rsg.setText(App.getInstance().direction);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_login_back:
			back();
			break;
		case R.id.tv_login_rsg:
			if (countyList.size() != 0) {
				//	showPopup(v);
				Intent intent = new Intent(this,AddressCountyActivity.class);
				intent.putExtra("countyList", (Serializable)countyList);
				startActivity(intent);
			}
			break;
		default:
			break;
		}
	}	

	@Override
	public void onResume() {
		super.onResume();
		if (!CommonUtils.isNull_nie(App.street_id)) {
			tv_login_rsg.setText(App.street_name);
			county_id = App.county_id;
			reqStoreList(true);
		}else if (!CommonUtils.isNull_nie(App.county_id)) {
			tv_login_rsg.setText(App.county_name);
			county_id = App.county_id;
			reqStoreList(true);
		}

	}
	private void reqCounty() {
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		showDialog(null);
		App.cityId = "SZ";
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("pid", App.cityId);

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.areaList,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo.result+"");

				dismissLoadingDialog();
				if (responseInfo.result.length() != 0) {


					try {
						JSONArray jsonObject = new JSONArray(responseInfo.result);

						Gson gson = new Gson();
						System.out.println("jsonObject.toString()::"+jsonObject.toString());

						countyList = gson.fromJson(jsonObject.toString(), new TypeToken<List<CountyList>>() {
						}.getType());

//						if (countyList.size() != 0) {
//							tv_login_rsg.setText(countyList.get(0).getNAME());
//							county_id = countyList.get(0).getID();
//						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				dismissLoadingDialog();
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.get_country_failure);
			}
		});
	}
	private void reqStoreList(final boolean refresh) {
		//		province_id:省份ID
		//		city_id:市ID
		//		county_id:区县ID
		//		street_id:街道ID
		//		type:店铺类型(0订座,1外卖,2挂号)
		//		out_type:外卖类型ID
		if (refresh) {
			shopList1.clear();
			page = 1;
		}else {
			page++;
		}
		

		showDialog(null);
		RequestParams params = new RequestParams();
		
		int type = 0;
		if (BaseConstant.DINGZUO == App.getInstance().type) {
			type = 0;
			params.addQueryStringParameter("province_id", "");
			params.addQueryStringParameter("city_id", App.cityId);
			params.addQueryStringParameter("county_id", county_id);
			params.addQueryStringParameter("street_id",App.street_id);
		}else if (BaseConstant.GUAHAO == App.getInstance().type) {
			type = 2;
		}
		params.addQueryStringParameter("type", type+"");
		params.addQueryStringParameter("out_type", "");
		params.addQueryStringParameter("page", page+"");

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.shopList,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("shopList——onSuccess==", responseInfo.result+"");

				dismissLoadingDialog();
				if (responseInfo.result.length() != 0) {
					try {
						JSONArray jsonObject = new JSONArray(responseInfo.result);

						Gson gson = new Gson();
						System.out.println("jsonObject.toString()::"+jsonObject.toString());

						shopList = gson.fromJson(jsonObject.toString(), new TypeToken<List<ShopList>>() {
						}.getType());

//						if (shopList.size() == 0) {
//							empty_relat.setVisibility(View.VISIBLE);
//							xlistView.setVisibility(View.GONE);
//							NewToast.makeText(getApplicationContext(), "暂时没有数据");
//						}else {
//							empty_relat.setVisibility(View.GONE);
//							xlistView.setVisibility(View.VISIBLE);
//						}
						Log.i(tag, shopList1.toString());
						int select = shopList1.size();
						if (shopList.size() != 0) {
							shopList1.addAll(shopList);
						}
						madapter = new DingZuoAdapter(DingZuoActivity.this,shopList1);
						xlistView.setAdapter(madapter);
						xlistView.setSelection(select);
						xlistView.onRefreshComplete();

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				dismissLoadingDialog();
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.get_shop_failure);
			}
		});

	}
	/**显示地区弹出框 */
	private void showPopup(View v){
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < countyList.size(); i++) {
			list.add(countyList.get(i).getNAME());
		}
		TitlePopupwindow title = new TitlePopupwindow(DingZuoActivity.this, list);
		int[] location = new int[2];
		v.getLocationInWindow(location);
		location[1] = location[1] + dingzuo_titlebar_content.getHeight()-35;
		ScreenSizeUtil util = new ScreenSizeUtil(DingZuoActivity.this);
		int width = util.getScreenWidth();
		int height = util.getScreenHeight();
		title.showAt(location, width, height);
		title.setItemClickListener(new IDropdownItemClickListener() {

			@Override
			public void onItemClick(String text, int drawableId) {
				tv_login_rsg.setText(text);

				for (int i = 0; i < countyList.size(); i++) {
					if (text.equals(countyList.get(i).getNAME())) {
						//	countyId = countyList.get(i).getID();
					}
				}
			}
		});
	}

	@Override
	public void onRefresh(int page) {
		reqStoreList(true);
	}

	@Override
	public void onLoadMore(int page) {
		reqStoreList(false);
	}
}
